<template>
  <view class="exam-container">
    <!-- 顶部统计 -->
    <view class="stats-bar">
      <view class="stats-item">
        <text class="number">{{ totalQuestions }}</text>
        <text class="label">测试总数</text>
      </view>
      <view class="stats-item">
        <text class="number highlight">{{ correctCount }}</text>
        <text class="label">已完成</text>
      </view>
      <view class="stats-item">
        <text class="number">{{ wrongCount }}</text>
        <text class="label">未完成</text>
      </view>
    </view>

    <!-- 应用卡片网格 -->
    <view class="question-grid" v-if="!showQuestion">
      <view 
        v-for="(item, index) in questionList" 
        :key="index"
        class="question-card"
        :class="{ 
          'type-mbti': item.appType === 1,
          'type-score': item.appType === 0,
          'current': currentIndex === index 
        }"
        @click="selectQuestion(index)"
      >
        <view class="card-content">
          <view class="card-header">
            <image 
              class="author-avatar" 
              :src="item.user?.userAvatar || 'https://gitee.com/static/images/logo-black.svg'" 
              mode="aspectFill"
            />
            <text class="author-name">{{ item.user?.userName || '未知用户' }}</text>
          </view>
          <text class="question-title">{{ item.appName }}</text>
          <text class="question-subject">{{ item.appDesc }}</text>
          <view class="app-info">
            <text class="app-type">{{ item.appType === 1 ? '测评类测试' : '得分类测试' }}</text>
            <text class="create-time">{{ formatDate(item.createTime) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 答题页面 -->
    <view class="question-view" v-else>
      <!-- 应用信息头部 -->
      <view class="app-header">
        <view class="app-info">
          <text class="app-name">{{ currentApp.appName }}</text>
          <text class="app-type">{{ currentApp.appType === 1 ? '得分类测试' : '测评类测试' }}</text>
        </view>
        <text class="app-desc">{{ currentApp.appDesc }}</text>
        <view class="author-info">
          <image 
            class="author-avatar" 
            :src="currentApp.user?.userAvatar" 
            mode="aspectFill"
          />
          <text class="author-name">{{ currentApp.user?.userName }}</text>
        </view>
      </view>

      <!-- 题目内容 -->
      <view class="question-content" v-if="currentQuestion">
        <text class="question-text">{{ currentQuestion.content }}</text>
        
        <view class="options-list">
          <view 
            v-for="(option, index) in currentQuestion.options" 
            :key="index"
            class="option-item"
            :class="{ selected: selectedAnswer === index }"
            @click="selectAnswer(index)"
          >
            <text class="option-label">{{ ['A', 'B', 'C', 'D'][index] }}</text>
            <text class="option-text">{{ option }}</text>
          </view>
        </view>
      </view>
      
      <view class="action-buttons">
        <button class="btn prev" @click="prevQuestion">上一题</button>
        <button class="btn submit" @click="submitAnswer">提交答案</button>
        <button class="btn next" @click="nextQuestion">下一题</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request.js'

const totalQuestions = ref(0)
const correctCount = ref(0)
const wrongCount = ref(0)
const currentIndex = ref(0)
const questionList = ref([])
const showQuestion = ref(false)
const currentApp = ref({})
const currentQuestion = ref(null)
const selectedAnswer = ref(null)
const currentQuestionIndex = ref(0)

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取应用列表
const getAppList = async () => {
  try {
    const res = await request({
      url: '/api/app/list/page/vo',
      method: 'POST',
      data: {
        current: 1,
        pageSize: 12,
        reviewStatus: 1,
        sortField: "createTime",
        sortOrder: "descend"
      }
    })
    
    if (res.code === 0 && res.data) {
      questionList.value = res.data.records
      totalQuestions.value = res.data.total || 0
      
      // 统计测试类型
      const stats = questionList.value.reduce((acc, curr) => {
        if (curr.appType === 1) acc.mbti++
        else acc.score++
        return acc
      }, { mbti: 0, score: 0 })
      
      correctCount.value = stats.mbti
      wrongCount.value = stats.score
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    uni.showToast({
      title: '获取列表失败',
      icon: 'none'
    })
  }
}

const selectQuestion = async (index) => {
  const appId = questionList.value[index]?.id
  if (!appId) {
    uni.showToast({
      title: '无效的应用ID',
      icon: 'none'
    })
    return
  }
  
  // 使用正确的页面路径格式
  uni.navigateTo({
    url: `/pages/exam/detail?id=${appId}`,
    fail: (err) => {
      console.error('页面跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 获取题目列表
const getQuestionList = async (appId) => {
  if (!appId) return
  
  try {
    const res = await request({
      url: '/api/question/list/page/vo',
      method: 'POST',
      data: {
        current: 1,
        pageSize: 100,
        appId,
        sortField: 'createTime',
        sortOrder: 'desc'
      }
    })
    
    if (res.code === 0 && res.data?.records) {
      questionList.value = res.data.records
      currentQuestionIndex.value = 0
      // 加载第一题
      if (questionList.value[0]) {
        loadQuestion(questionList.value[0])
      }
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
  }
}

// 加载题目内容
const loadQuestion = (question) => {
  const questionContent = question.questionContent?.[0] || {}
  currentQuestion.value = {
    content: questionContent.title || '',
    options: questionContent.options?.map(opt => opt.value) || []
  }
}

// 返回列表
const backToList = () => {
  showQuestion.value = false
  currentApp.value = {}
  currentQuestion.value = null
  selectedAnswer.value = null
  currentQuestionIndex.value = 0
}

// ... 其他答题相关方法

onMounted(() => {
  getAppList()
})
</script>

<style scoped>
.exam-container {
  padding: 20rpx;
  background: #f5f6fa;
  min-height: 100vh;
}

.stats-bar {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-item .number {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stats-item .number.highlight {
  color: #4CAF50;
}

.stats-item .label {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 10rpx;
}

.question-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
  transition: all 0.3s ease;
}

.question-card:active {
  transform: scale(0.98);
}

.question-card.type-mbti {
  border-left: 8rpx solid #4CAF50;
}

.question-card.type-score {
  border-left: 8rpx solid #2196F3;
}

.question-card.current {
  background: #E3F2FD;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.question-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.question-subject {
  font-size: 26rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.app-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
  font-size: 24rpx;
}

.app-type {
  color: #4CAF50;
  background: #E8F5E9;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.create-time {
  color: #999;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.author-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  margin-right: 12rpx;
}

.author-name {
  font-size: 24rpx;
  color: #666;
}

.card-content {
  display: flex;
  flex-direction: column;
}

.question-title {
  margin-top: 8rpx;
}

.question-view {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: #f5f6fa;
  z-index: 100;
  padding: 30rpx;
  box-sizing: border-box;
}
</style> 